import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { loginAccount, getSmsCaptcha, compareCaptcha, getToken } from '@/services/userApi';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { casLogoutUrl } from '@/defaultSettings';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(loginAccount, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *getToken({ payload }, { call, put }) {
      const response = yield call(getToken, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/home'));
        return { status: 'ok', message: '登录成功' };
      } else {
        return response;
      }
    },

    *ssoLogin({ payload }, { call, put }) {
      const response = yield call(loginAccount, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/home'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getSmsCaptcha, payload);
    },
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      localStorage.removeItem('cancersystem_token');
      localStorage.removeItem('cancersystem_menu');
      localStorage.removeItem('cancersystem_menubutton');
      localStorage.removeItem('cancersystem_tid');
      localStorage.setItem('cancersystem_authority', 'guest');
      reloadAuthorized();
      const { redirect } = getPageQuery();
      // redirect
      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          })
        );
      }
      // cas的登出地址不为空时,将地址重定向为cas登出地址
      if (casLogoutUrl != '') {
        window.location.replace('http://222.249.173.24:84/ah_base/login/logout.jsp');
      }
    },
    *compareCaptcha({ payload }, { call, put }) {
      const response = yield call(compareCaptcha, payload);
      console.log(JSON.stringify(response));
      yield put({
        type: 'save',
        payload: response,
      });
      if (!response.message) return;
      return response;
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.currentAuthority) {
        setAuthority(payload.currentAuthority);
      } else {
        localStorage.setItem('cancersystem_authority', 'guest');
      }
      return {
        ...state,
        status: payload ? payload.status : false,
        type: payload ? payload.type : '',
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload.data,
      };
    },
  },
};
